<template>
	<view class="p30">
		<view class="mtb20">
			<u-steps current="1" activeColor="#06B7F3" inactiveColor="#C9D3E9">
				<u-steps-item title="信息输入">
				</u-steps-item>
				<u-steps-item title="车辆验证"></u-steps-item>
				<u-steps-item title="注册成功"></u-steps-item>
			</u-steps>
		</view>
		<view class="pl30">
			<view class="flex-align-center mt60">
				<view class="mr10 bold circle3 c-white" style="background-color:#ECAD00;">1</view>
				<text class="f24">请确保手机蓝牙、地理位置、微信蓝牙权限处于开启状态</text>
			</view>
			<view class="flex-align-center mt30">
				<view class="mr10 bold circle3 c-white" style="background-color:#ECAD00;">2</view>
				<text class="f24">请确保车辆处于通电状态</text>
			</view>
			<view class="flex-align-center mt30">
				<view class="mr10 bold circle3 c-white" style="background-color:#ECAD00;">3</view>
				<text class="f24">验证时，请勿离开当前页面</text>
			</view>
			<view class="flex-align-center mt30">
				<view class="mr10 bold circle3 c-white" style="background-color:#ECAD00;">4</view>
				<text class="f24">点击【验证按钮】</text>
			</view>
			<view class="flex-center mt60" style="height: 140px;height:140px">
				<u--image src="https://iot-device-saas.oss-cn-shenzhen.aliyuncs.com/public/blue.gif" width="140px"
					height="140px" v-if="!$validatenull(bluetoothContent)"></u--image>
			</view>
			<view class="flex-center">
				<view style="width: 150px;" class="mt100">
					<u-button type="primary" text="验证" :throttleTime="1000" @click="checkBlueConnect"
						v-if="$validatenull(bluetoothContent)"></u-button>

					<u-button v-if="!isProduct" type="primary" text="绑定" :throttleTime="1000" @click="bindCarFun"
						:customStyle="{marginTop:'60rpx'}"></u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		bindCarAPI
	} from "@/api/api/car.js"
	import {
		bluetoothStart,
		closeBLEConnection,
		setBlueConnectTimer
	} from "@/static/bluetooth/core.js"
	import {
		dataPointMqttTopic,
		fenceMqttTopic,
		authTopic
	} from '@/api/http/setting';
	import {
		$getCarDetail,
		mqttMSG,
		$currentRoute,
		client,
		throttle
	} from "@/utils/utils.js"

	import {
		mapState
	} from 'vuex'
	import {
		getStoreSyncUtil
	} from "@/utils/store.js"
	export default {
		data() {
			return {
				licensePlateNumber: '',
				nickName: '',
				ecuId: '',
				id: '',
				engineNum: '',
			}
		},
		onLoad(option) {
			console.log('option', option)
			this.nickName = option.nickName;
			this.engineNum = option.engineNum;
			this.licensePlateNumber = option.licensePlateNumber;
			this.id = option.id;
		},
		onShow() {
			console.log("client", client);
			//清除定时器
			if (!this.$validatenull(this.blueConnectTimer)) {
				clearInterval(this.blueConnectTimer);
			}
			this.$store.commit("setBluetoothContent", "");
		},
		computed: {
			// 将vuex的state中的所有变量，解构到全局混入的mixin中
			...mapState(["currentBike", "isToIndex", "deviceData", "blueConnectTimer", "lastBike", "isConnected",
				"bluetoothContent","isProduct"
			])
		},
		//如果页面返回，需要重新处理蓝牙连接 1、未连接上绑定设备；2、连接上绑定设备，但是未点击绑定，3、连接上绑定设备，并点击了绑定并成功绑定
		onUnload() {
			if (!this.isToIndex) {
				let currentRoute = $currentRoute();
				if (currentRoute == "pagesMy/views/addDevice" || currentRoute == "pagesMy/views/deviceVerify") {
					if (this.isConnected) {
						if (this.$store.state.bluetoothDevice.name != this.deviceData
							.ecuId) { //2、连接上绑定设备，但是未点击绑定 ,此时的连接设备与当前设备不一致
							closeBLEConnection(this.$store.state.bluetoothDevice, () => {
								bluetoothStart();
							});
						}
					} else {
						this.blueConnectFail();
					}
				}
			}

		},
		watch: {
			"isConnected": {
				handler(val) {
					//如果连接成功，在直接发送指令
					if (val && this.$store.state.bluetoothDevice.name == this.lastBike.ecuId) {
						//连接成功,直接绑定设备
						this.$store.commit("setBluetoothContent", "");
						this.bindCarFun();
						//绑定成功后，新开启定时器
						setBlueConnectTimer();
					} else if (this.$store.state.bluetoothDevice.name == this.lastBike.ecuId) {
						this.blueConnectFail();
					}
				}
			},
		},
		methods: {
			blueConnect(isOpenTimer) {
				if (this.isConnected) {
					closeBLEConnection(this.$store.state.bluetoothDevice, () => {
						bluetoothStart(isOpenTimer);
					});
				} else {
					bluetoothStart(isOpenTimer);
				}
			},
			checkBlueConnect:throttle(function(){
				this.$store.commit("setIsOpenTimer", false);
				this.$store.commit("setBlueCurrentToConnectDevice", {
					ecuId: this.lastBike.ecuId
				})
				
				this.blueConnect(false);
				
			}),
			//如果蓝牙连接失败，则需要重新连回原来的设备
			blueConnectFail() {
				this.$store.commit("setBlueCurrentToConnectDevice", {
					ecuId: this.currentBike.ecuId
				})
				this.blueConnect();
			},
			//如果蓝牙能连接成功，则正常绑定，就不用管蓝牙
			bindCarFun: throttle(function() {
				console.log("车辆绑定");
				bindCarAPI({
					id: this.id,
					licensePlateNumber: this.licensePlateNumber,
					engineNum: this.engineNum,
					nickName: this.nickName,
				}).then(([err, data]) => {
					if (err) return;
					this.$navigateTo('/pagesMy/views/addDeviceSuccess?id=' + this.lastBike.id)
					//绑定成功，设置为默认车辆,切换mqtt和蓝牙连接
					$getCarDetail(this.lastBike.id, () => {
						let currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
						//let currentRoute = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
						console.log("currentRoutes===deviceVerify", currentRoutes);
						let oldEcuid = this.currentBike.ecuId;
						let topicalDataPoint = dataPointMqttTopic + this.currentBike
							.ecuId; //上报数据推送
						let isCrossFence = fenceMqttTopic + this.currentBike.ecuId; //电子围栏是否超出区域推送
						let isAuthTopic = authTopic + this.currentBike.ecuId; //电子围栏是否超出区域推送
						if (!this.$validatenull(client) && client
							.connected) { // 如果当前处于连接状态，则不在重新连接，则直接取消订阅和重新订阅
							client.unsubscribe([topicalDataPoint, isCrossFence, isAuthTopic],
								async error => {
									if (!error) {
										console.log("取消订阅成功");
									} else {
										console.log("取消订阅失败");
									}
								});
							topicalDataPoint = dataPointMqttTopic + this.lastBike.ecuId; //上报数据推送
							isCrossFence = fenceMqttTopic + this.lastBike.ecuId; //电子围栏是否超出区域推送
							isAuthTopic = authTopic + this.lastBike.ecuId; //电子围栏是否超出区域推送
							client.subscribe([topicalDataPoint, isCrossFence, isAuthTopic],
								async error => {
									if (!error) {
										console.log("订阅成功");
									} else {
										console.log("订阅失败");
									}
								});
							this.$store.commit("setCurrentBike", this.lastBike);

						} else { //如果没有连接，则重新连接订阅
							this.$store.commit("setCurrentBike", this.lastBike);
							mqttMSG();
						}

					});

				});
			})
		}
	}
</script>

<style>
</style>
